package com.famnote.getitbeauty;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.StringTokenizer;



import org.jivesoftware.smack.XMPPConnection;

/*
import ncsu.course.android.broadcastchat4.BroadcastChatService;
import ncsu.course.android.broadcastchat4.CreateRoomActivity;
import ncsu.course.android.broadcastchat4.FindRoomActivity;
import ncsu.course.android.broadcastchat4.R;
import ncsu.course.android.broadcastchat4.UserNameActivity;
import ncsu.course.android.broadcastchat4.BroadcastChat.ChatMessageBuilder;
import ncsu.course.android.broadcastchat4.BroadcastChat.ChatMessageChecker;
*/



import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.MessageQueue;
import android.renderscript.Element;
import android.telephony.TelephonyManager;
//import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.EditorInfo;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.VideoView;


import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.OrFilter;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.provider.PrivacyProvider;
import org.jivesoftware.smack.provider.ProviderManager;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.Form;
import org.jivesoftware.smackx.FormField;
import org.jivesoftware.smackx.GroupChatInvitation;
import org.jivesoftware.smackx.PrivateDataManager;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import org.jivesoftware.smackx.bytestreams.socks5.provider.BytestreamsProvider;
import org.jivesoftware.smackx.filetransfer.FileTransfer;
import org.jivesoftware.smackx.filetransfer.FileTransferListener;
import org.jivesoftware.smackx.filetransfer.FileTransferManager;
import org.jivesoftware.smackx.filetransfer.FileTransferNegotiator;
import org.jivesoftware.smackx.filetransfer.FileTransferRequest;
import org.jivesoftware.smackx.filetransfer.OutgoingFileTransfer;

import org.jivesoftware.smackx.filetransfer.IncomingFileTransfer;

import org.jivesoftware.smackx.muc.DefaultParticipantStatusListener;
import org.jivesoftware.smackx.muc.HostedRoom;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.smackx.muc.ParticipantStatusListener;
import org.jivesoftware.smackx.muc.RoomInfo;
import org.jivesoftware.smackx.packet.ChatStateExtension;
import org.jivesoftware.smackx.packet.LastActivity;
import org.jivesoftware.smackx.packet.OfflineMessageInfo;
import org.jivesoftware.smackx.packet.OfflineMessageRequest;
import org.jivesoftware.smackx.packet.SharedGroupsInfo;
import org.jivesoftware.smackx.provider.AdHocCommandDataProvider;
import org.jivesoftware.smackx.provider.DataFormProvider;
import org.jivesoftware.smackx.provider.DelayInformationProvider;
//import org.jivesoftware.smackx.provider.BytestreamsProvider;
import org.jivesoftware.smackx.provider.DiscoverInfoProvider;
import org.jivesoftware.smackx.provider.DiscoverItemsProvider;
import org.jivesoftware.smackx.provider.MUCAdminProvider;
import org.jivesoftware.smackx.provider.MUCOwnerProvider;
import org.jivesoftware.smackx.provider.MUCUserProvider;
import org.jivesoftware.smackx.provider.MessageEventProvider;
import org.jivesoftware.smackx.provider.MultipleAddressesProvider;
import org.jivesoftware.smackx.provider.RosterExchangeProvider;
import org.jivesoftware.smackx.provider.VCardProvider;
import org.jivesoftware.smackx.provider.XHTMLExtensionProvider;
//import org.jivesoftware.smackx.provider.IBBProviders;
import org.jivesoftware.smackx.provider.StreamInitiationProvider;
import org.jivesoftware.smackx.search.UserSearch;
import org.json.JSONArray;
import org.json.JSONObject;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.famnote.getitbeauty.R;

///import com.famnote.street.R;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import android.os.AsyncTask;

import android.provider.MediaStore;
import android.provider.Settings.Secure;

import android.media.ExifInterface;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;

import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;


/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 * 
 * @see SystemUiHider
 */
public class GroupChatActivity extends Activity {

	
	// Debugging
    private static final String TAG = "GroupChatActivity";
    private static final boolean D = true;

    // Message types sent from the BluetoothChatService Handler
    public static final int MESSAGE_READ 	= 1;
    public static final int MESSAGE_WRITE 	= 2;
    public static final int MESSAGE_TOAST 	= 3;
    
    public static final String ROOM_LIST 			= "room_list";
    private static final long FIND_ROOM_TIME_OUT 	= 2000;
    private ArrayList<String> existingRoomList 		= null;
    private static final int RANDOM_WAIT_WIN 		= 500;
    
    // Key names received from the BroadcastChatService Handler
    public static final String TOAST = "toast";

    // Intent request codes
    private static final int INTENT_GET_USERNAME 	= 1;
    private static final int INTENT_CREATE_ROOM 	= 2;
    private static final int INTENT_FIND_ROOM		= 3;

	private VideoView mVideoView;
	private WebView mWebView;
    
    //private ArrayList<String> messages = new ArrayList<String>();
    private ArrayList<OneComment> messages = new ArrayList<OneComment>();
    
    private Handler mHandler = new Handler();
    
    private DiscussArrayAdapter mAdapter;
    
    
	// Layout Views
    //private TextView 	mTitle;
    private ListView 	mConversationView;
    private EditText 	mOutEditText;
    private Button 		mSendButton;

    // Array adapter for the conversation thread
    //private ArrayAdapter<String> mConversationArrayAdapter;
    // String buffer for outgoing messages
    private StringBuffer mOutStringBuffer;
    // Member object for the chat services
    //////private BroadcastChatService mChatService = null;
    
    
    // message format
    private static final String CMD 	= "cmd=";
    private static final String ROOM 	= "room=";
    private static final String BODY 	= "body=";
    private static final String CMD_FIND_ROOM 		= "1";
    private static final String CMD_ROOM_NAME_ACK 	= "2";
    private static final String CMD_MESSAGE 		= "3";
    private static final String DELIMITER			= "||";

	private static final int CHOOSER_IMAGE_REQUEST_CODE = 0;
        
    //user and room name
    //private String mUserName;
    //private String mRoomName = "room1";
    
    
    
    //private SettingsDialog mDialog;
    private XMPPConnection connection;
    
    private String mPartner;
    
    
    private String mUserid;
    
    private MultiUserChat mMuc;
    
    private String mRoomid;
    private String mNickname;
    private String mRoomTitle;
    private String mRoomSubtitle;
    private String mRoomDisplayUrl;
    
    ProgressDialog progDailog;
    private ProgressDialog dialog;
    
    private Dialog mDashDialog;

   // private ImageChooser imageChooser;
    
    private Activity activity;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_group_chat);

		
		activity = this;
		
		Bundle b = getIntent().getExtras();
		mRoomid = b.getString("roomid");
		mNickname = b.getString("nickname");
		
		
        //dialog = ProgressDialog.show(activity, "", getResources().getString(R.string.loading), true);

        GetDisplayTask task = new GetDisplayTask();

        String url = "http://push.appaas.com/hulbox/of_get_display.php?roomid=" + mRoomid;

        task.execute(url);

		//mDashDialog = new Dialog(this);
		

        // ImageLoader class instance
        //ImageLoader imgLoader = new ImageLoader(getApplicationContext());
 
        // whenever you want to load an image from url
        // call DisplayImage function
        // url - image url to load
        // loader - loader image, will be displayed before getting image
        // image - ImageView
        
        //ImageView bgImageView = (ImageView)findViewById(R.id.imageView1);
        //imgLoader.DisplayImage(mRoomImageUrl, bgImageView);
		
        


        mVideoView = (VideoView)findViewById(R.id.videoView);
        mWebView = (WebView) findViewById(R.id.webview);
        
        
        setupChat();
 
	}
	
	private class GetDisplayTask extends AsyncTask<String, Integer, String>{
	        String data = null;
	                
	        @Override
	        protected String doInBackground(String... url) {
	                        try{
	                            data = downloadUrl(url[0]);
	                                
	                        }catch(Exception e){
	                        	Log.d("Background Task",e.toString());
	                        }
	                        if(D) Log.e(TAG, "nickname: " + data);
	                        
	                        return data;
	        }

	        @Override
	        protected void onPostExecute(String result) {
	                	
	             //dialog.dismiss();
	                	
	             if ((data == null) || (data == "")) {
	            		
	             } else {
	            	 
	            	 mRoomDisplayUrl = data;

	    			
	                 Uri uri = Uri.parse(mRoomDisplayUrl);
	                 
	                 String scheme = uri.getScheme();
	                 
	                 if (scheme.equals("rtsp")) {
	             
	                 	mWebView.setVisibility(View.INVISIBLE);
	                 	mVideoView.setVisibility(View.VISIBLE);
	                 	
	                 	//mVideoView.setMediaController(new MediaController(this));
	                 	mVideoView.setVideoURI(uri);
	                 	mVideoView.requestFocus();
	                 	mVideoView.start();
	                
	                 	String msg = getResources().getString(R.string.please_wait);
	                 	progDailog = ProgressDialog.show(activity, "", msg, true);

	                 	mVideoView.setOnPreparedListener(new OnPreparedListener() {

	                 		public void onPrepared(MediaPlayer mp) {
	                 			// TODO Auto-generated method stub
	                 			progDailog.dismiss();
	                 		}
	                 	});
	                 } else if (scheme.equals("http")) {
	                 	
	                 	mVideoView.setVisibility(View.INVISIBLE);
	                 	mWebView.setVisibility(View.VISIBLE);
	                 	
	                     mWebView.getSettings().setJavaScriptEnabled(true); 
	                     //mWebView.loadUrl("http://push.appaas.com/directory/www");
	                     mWebView.loadUrl(mRoomDisplayUrl);
	                 }
	                 
	                 
	                 
	                 //mVideoView.setVideoURI(uri);
	                 //mVideoView.start();
	                 
	                 
	                 //YourAsyncTask yourAsyncTask = new YourAsyncTask();

	                 // Starting the download process
	                 //yourAsyncTask.execute();
	                 
	         		
	            	 
	             }
	                	
	        }
	}
	
	
	
	
	
	private class YourAsyncTask extends AsyncTask<Void, Void, Void>
    {
		String videoUrl;
		
        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(activity, "", "Loading Video wait...", true);
        }

        @Override
        protected Void doInBackground(Void... params)
        {
            try
            {
                String url = "http://www.youtube.com/watch?v=1FJHYqE0RDg";
                videoUrl = getUrlVideoRTSP(url);
                Log.e("Video url for playing=========>>>>>", videoUrl);
            }
            catch (Exception e)
            {
                Log.e("Login Soap Calling in Exception", e.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result)
        {
            super.onPostExecute(result);
            progressDialog.dismiss();
/*
            videoView.setVideoURI(Uri.parse("rtsp://v4.cache1.c.youtube.com/CiILENy73wIaGQk4RDShYkdS1BMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp"));
            videoView.setMediaController(new MediaController(AlertDetail.this));
            videoView.requestFocus();
            videoView.start();*/            
            mVideoView.setVideoURI(Uri.parse(videoUrl));
            MediaController mc = new MediaController(activity);
            mVideoView.setMediaController(mc);
            mVideoView.requestFocus();
            mVideoView.start();          
            mc.show();
        }

    }

	public static String getUrlVideoRTSP(String urlYoutube)
    {
        try
        {
            String gdy = "http://gdata.youtube.com/feeds/api/videos/";
            DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            String id = extractYoutubeId(urlYoutube);
            URL url = new URL(gdy + id);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            Document doc = documentBuilder.parse(connection.getInputStream());
            
            org.w3c.dom.Element el = doc.getDocumentElement();
            
            NodeList list = el.getElementsByTagName("media:content"); ///media:content
           
            
            String cursor = urlYoutube;
            for (int i = 0; i < list.getLength(); i++)
            {
                Node node = list.item(i);
                if (node != null)
                {
                    NamedNodeMap nodeMap = node.getAttributes();
                    HashMap<String, String> maps = new HashMap<String, String>();
                    for (int j = 0; j < nodeMap.getLength(); j++)
                    {
                        Attr att = (Attr) nodeMap.item(j);
                        maps.put(att.getName(), att.getValue());
                    }
                    if (maps.containsKey("yt:format"))
                    {
                        String f = maps.get("yt:format");
                        if (maps.containsKey("url"))
                        {
                            cursor = maps.get("url");
                        }
                        if (f.equals("1"))
                            return cursor;
                    }
                }
            }
            return cursor;
        }
        catch (Exception ex)
        {
            Log.e("Get Url Video RTSP Exception======>>", ex.toString());
        }
        return urlYoutube;

    }

	protected static String extractYoutubeId(String url) throws MalformedURLException
    {
        String id = null;
        try
        {
            String query = new URL(url).getQuery();
            if (query != null)
            {
                String[] param = query.split("&");
                for (String row : param)
                {
                    String[] param1 = row.split("=");
                    if (param1[0].equals("v"))
                    {
                        id = param1[1];
                    }
                }
            }
            else
            {
                if (url.contains("embed"))
                {
                    id = url.substring(url.lastIndexOf("/") + 1);
                }
            }
        }
        catch (Exception ex)
        {
            Log.e("Exception", ex.toString());
        }
        return id;
    }	
	
	
	
	
	
	public class ModalDialog {

		private boolean mChoice = false;        
		private boolean mQuitModal = false;     

		private Method mMsgQueueNextMethod = null;
		private Field mMsgTargetFiled = null;

		public ModalDialog() {
		}

		public void showAlertDialog(Context context, String info) {
		    if (!prepareModal()) {
		        return;
		    }

		    // build alert dialog
		    AlertDialog.Builder builder = new AlertDialog.Builder(context);
		    builder.setMessage(info);
		    builder.setCancelable(false);
		    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int id) {
		            ModalDialog.this.mQuitModal = true;
		            dialog.dismiss();
		        }
		    });

		    AlertDialog alert = builder.create();
		    alert.show();

		    // run in modal mode
		    doModal();
		}

		public boolean showConfirmDialog(Context context, String info) {
		    if (!prepareModal()) {
		        return false;
		    }

		    // reset choice
		    mChoice = false;

		    AlertDialog.Builder builder = new AlertDialog.Builder(context);
		    builder.setMessage(info);
		    builder.setCancelable(false);
		    builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int id) {
		            ModalDialog.this.mQuitModal = true;
		            ModalDialog.this.mChoice = true;
		            dialog.dismiss();
		        }
		    });

		    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int id) {
		            ModalDialog.this.mQuitModal = true;
		            ModalDialog.this.mChoice = false;
		            dialog.cancel();
		        }
		    });

		    AlertDialog alert = builder.create();
		    alert.show();

		    doModal();
		    return mChoice;
		}

		private boolean prepareModal() {
		    Class<?> clsMsgQueue = null;
		    Class<?> clsMessage = null;

		    try {
		        clsMsgQueue = Class.forName("android.os.MessageQueue");
		    } catch (ClassNotFoundException e) {
		        e.printStackTrace();
		        return false;
		    }

		    try {
		        clsMessage = Class.forName("android.os.Message");
		    } catch (ClassNotFoundException e) {
		        e.printStackTrace();
		        return false;
		    }

		    try {
		        mMsgQueueNextMethod = clsMsgQueue.getDeclaredMethod("next", new Class[]{});
		    } catch (SecurityException e) {
		        e.printStackTrace();
		        return false;
		    } catch (NoSuchMethodException e) {
		        e.printStackTrace();
		        return false;
		    }

		    mMsgQueueNextMethod.setAccessible(true);

		    try {
		        mMsgTargetFiled = clsMessage.getDeclaredField("target");
		    } catch (SecurityException e) {
		        e.printStackTrace();
		        return false;
		    } catch (NoSuchFieldException e) {
		        e.printStackTrace();
		        return false;
		    }

		    mMsgTargetFiled.setAccessible(true);
		    return true;
		}

		private void doModal() {
		    mQuitModal = false;

		    // get message queue associated with main UI thread
		    MessageQueue queue = Looper.myQueue();
		    while (!mQuitModal) {
		        // call queue.next(), might block
		        android.os.Message msg = null;
		        try {
		            msg = (android.os.Message)mMsgQueueNextMethod.invoke(queue, new Object[]{});
		        } catch (IllegalArgumentException e) {
		            e.printStackTrace();
		        } catch (IllegalAccessException e) {
		            e.printStackTrace();
		        } catch (InvocationTargetException e) {
		            e.printStackTrace();
		        }

		        if (null != msg) {
		            Handler target = null;
		            try {
		                target = (Handler)mMsgTargetFiled.get(msg);
		            } catch (IllegalArgumentException e) {
		                e.printStackTrace();
		            } catch (IllegalAccessException e) {
		                e.printStackTrace();
		            }

		            if (target == null) {
		                // No target is a magic identifier for the quit message.
		                mQuitModal = true;
		            }

		            target.dispatchMessage(msg);
		            msg.recycle();
		        }
		    }
		}
		}
	
	
	
	

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);

		// Trigger the initial hide() shortly after the activity has been
		// created, to briefly hint to the user that UI controls
		// are available.
		
		//////////delayedHide(100);
	}

	
    public void onStart() {
        super.onStart();
        if(D) Log.e(TAG, "++ ON START ++");


    }
	
    public synchronized void onPause() {
        super.onPause();
        if(D) Log.e(TAG, "- ON PAUSE -");
        /////////if (mChatService != null) mChatService.stop();
        
    }

    public synchronized void onResume() {
        super.onResume();
        if(D) Log.e(TAG, "- ON RESUME -");
        
        //if (connection == null) {
        	//setupChat();
        //}
    }

    public void onStop() {
        super.onStop();
        if(D) Log.e(TAG, "-- ON STOP --");
        //////////if (mChatService != null) mChatService.stop();
 
    }


    public void onDestroy() {
        super.onDestroy();
        if(D) Log.e(TAG, "--- ON DESTROY ---");
        // Stop the Broadcast chat services
        //////////if (mChatService != null) mChatService.stop();
        
        
        if (mMuc != null) {
        	mMuc.leave();
        	mMuc = null;
        }
        
        
        if (connection != null) {
        	connection.disconnect();
        	connection = null;
        }
        
    }
    
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) { 
        if (keyCode == KeyEvent.KEYCODE_BACK) { 

        	//////String msg = getResources().getString(R.string.room_leaving);
        	//////dialog = ProgressDialog.show(this, "", msg, true);
        
        	
        	LeaveRoomTask task = new LeaveRoomTask();
        	
        	task.execute("http://push.appaas.com/hulbox/of_leave_room.php?roomid=" + mRoomid
        			+ "&userid=" + mUserid);
        	
        	
        	
            return true; 
        } 
        return super.onKeyDown(keyCode, event);
    }
    
    
    
    
    /** AsyncTask */
    private class LeaveRoomTask extends AsyncTask<String, Integer, String>{
        String data = null;
    	
        @Override
        protected String doInBackground(String... url) {
                
        	try{
        		
        		
                if (mMuc != null) {
                
                	mMuc.removeMessageListener(packetListener);
                	mMuc.removeParticipantStatusListener(participantStatusListener);
                	
                   	mMuc.leave();
                   	
                	mMuc = null;
                	
                }
                
                
                if (connection != null) {
                	
                	connection.disconnect();
                	
                	connection = null;
                }
                
                
        		data = downloadUrl(url[0]);
                                
            }catch(Exception e){
            	Log.d("Background Task",e.toString());
            }
            return data;
        }

        @Override
        protected void onPostExecute(String result) {
                	
        	///////dialog.dismiss();

        	finish();
        	
        	
        }
    }
	
	
    private void setupChat() {
        //Log.d(TAG, "setupChat()");

        // Initialize the array adapter for the conversation thread
        //mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
        //mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.multi_line_list_item);
        mConversationView = (ListView) findViewById(R.id.listView1);
        //mConversationView.setAdapter(mConversationArrayAdapter);

        messages.clear();
        
        mAdapter = new DiscussArrayAdapter(this, R.layout.listitem_discuss, messages);
        mConversationView.setAdapter(mAdapter);
        
        /*
        mOutEditText = (EditText) findViewById(R.id.edit_text_out);
        
        mOutEditText.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// If the event is a key-down event on the "enter" button
				if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
					// Perform action on key press
					mAdapter.add(new OneComment(false, mOutEditText.getText().toString()));
					////mConversationView.setSelection(mAdapter.getCount() -1);
					
					
					
					try {
		        		
			            if (mPartner != null) {
		            		Message msg = new Message(mPartner, Message.Type.chat);
		            		msg.setBody(mOutEditText.getText().toString());
		            		connection.sendPacket(msg);
		            	}
		        		
			            
			            
					} catch (Exception e) {
						e.printStackTrace();
					}
		        	
					
					mOutEditText.setText("");
					
					
					return true;
				}
				return false;
			}
		});
		*/
        
        
        
        // Initialize the compose field with a listener for the return key
        //mOutEditText = (EditText) findViewById(R.id.edit_text_out);
        
        //mOutEditText.setOnEditorActionListener(mWriteListener);

        // Initialize the send button with a listener that for click events
        mSendButton = (Button) findViewById(R.id.button_send);
        mSendButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	if(D) Log.e(TAG, "[sendButton clicked]");
            	
            	/*
                // Send a message using content of the edit text widget
                TextView view = (TextView) findViewById(R.id.edit_text_out);
                String message = view.getText().toString();
                sendMessage(message);        
                */
            	
            	mOutEditText = (EditText) findViewById(R.id.edit_text_out);
            	String message = mOutEditText.getText().toString();
            	
            
            	if (message.equals("")) return;
           	
            	
            	/*
            	messages.add(message);
            	// Add the incoming message to the list view
            	mHandler.post(new Runnable() {
            		public void run() {
            			//setListAdapter();
            			//ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.multi_line_list_item, messages);
            	        //DiscussArrayAdapter<OneComment> adapter =
            	        	//	new DiscussArrayAdapter<OneComment>(getApplicationContext(), R.layout.listitem_discuss, comments);
            	        //adapter.add(new OneComment(false, message));
            	        
            	        mConversationView.setAdapter(adapter);
            	        
            	        mConversationView.setSelection(adapter.getCount() -1);
            		}
            	});
            	*/
            	
            	/*
            	if (mRoomid != null) {
            		//Chat chat = connection.getChatManager().createChat("room1@")
            		try {
            			String to = mRoomid + "";
	            		Message msg = new Message(to, Message.Type.chat);
	            		msg.setBody(message);
	            		connection.sendPacket(msg);
	            	} catch (Exception e) {
	            		e.printStackTrace();
	            	}
            	}
            	*/
            	

            	//String room = mRoomid + "@conference.push.appaas.com";
        		try {
        			/*
                	Message msg = new Message(room, Message.Type.groupchat);
            		msg.setBody(message);
            		connection.sendPacket(msg);
            		*/
        			
            		mMuc.sendMessage(message);
            		
            	} catch (Exception e) {
            		e.printStackTrace();
            	}
        		

        		////messages.add(new OneComment(false, mNickName, message));
        		////if (messages.size() > 100) { messages.remove(0); }
            	
        		/*
        		// Add the incoming message to the list view
            	mHandler.post(new Runnable() {
            		public void run() {
            			setListAdapter();
            		}
            	});
            	*/
        		
        		mAdapter.notifyDataSetChanged();
        		mConversationView.setSelection(messages.size()-1);
            	
        		
        		mOutEditText.setText("");
        		/*
        		messages.add(new OneComment(false, message));
        		if (messages.size() > 100) { messages.remove(0); }
            	// Add the incoming message to the list view
            	mHandler.post(new Runnable() {
            		public void run() {
            			setListAdapter();
            			mOutEditText.setText("");
            		}
            	});
            	*/
            	
            	/*
            	if (mPartner == null) {
            		String notice = getResources().getString(R.string.no_partner);
            		
            		//mAdapter.add(new OneComment(true, notice));
            		//mConversationView.setSelection(mAdapter.getCount() -1);
            		
            		messages.add(new OneComment(true, notice));
            		if (messages.size() > 100) { messages.remove(0); }
                	// Add the incoming message to the list view
                	mHandler.post(new Runnable() {
                		public void run() {
                			setListAdapter();
                			mOutEditText.setText("");
                		}
                	});
            		
            	} else {
            		try {
	            		Message msg = new Message(mPartner, Message.Type.chat);
	            		msg.setBody(message);
	            		connection.sendPacket(msg);
	            	} catch (Exception e) {
	            		e.printStackTrace();
	            	}
	        	
            		//mAdapter.add(new OneComment(false, message));
            		//mConversationView.setSelection(mAdapter.getCount() -1);
            		
            		messages.add(new OneComment(false, message));
            		if (messages.size() > 100) { messages.remove(0); }
                	// Add the incoming message to the list view
                	mHandler.post(new Runnable() {
                		public void run() {
                			setListAdapter();
                			mOutEditText.setText("");
                		}
                	});
                	
                	
            	}
            	*/
            	
				
				
            	
            }
        });
        
        
        

        
        
        

        /*********************
        // Initialize the BluetoothChatService to perform bluetooth connections
        if(mChatService == null)
        	mChatService = new BroadcastChatService(this, mHandler);
        	*********************/

        // Initialize the buffer for outgoing messages
        if(mOutStringBuffer == null)
        	mOutStringBuffer = new StringBuffer("");
        
        
        
        
        /*
        Thread t = new Thread(new Runnable(){
        	@Override
        	public void run() {
        		
        		// no UI
        		mHandler.post(new Runnable(){
        			@Override
        			public void run() {
        				// UI OK
        				
        				if(D) Log.e(TAG, "++ XMPP connect ++");
        		        
        				ConnectionConfiguration connConfig =
        		        		new ConnectionConfiguration("push.appaas.com", 5222, "push.appaas.com");
        		        connConfig.setSASLAuthenticationEnabled(true);
        		        connConfig.setDebuggerEnabled(true);
        		        
        		        
        		        XMPPConnection connection = new XMPPConnection(connConfig);
        		        

        		        if(D) Log.e(TAG, "++ connection.connect() ++");
        		        
        		        try {
        		            connection.connect();
        		            
        		            if(D) Log.e(TAG, "++ after connection.connect() ++");
        		            
        		            
        		            
        		            connection.loginAnonymously();
        		            //Log.i("XMPPClient", "Logged in as " + connection.getUser());
        		            if(D) Log.e(TAG, "++ connection.loginAnonymously() ++");
        		            
        		            setConnection(connection);
        		            
        		        } catch (XMPPException ex) {
        		            Log.e("XMPPClient", "[SettingsDialog] Failed to connect to " + connection.getHost());
        		            Log.e("XMPPClient", ex.toString());
        		            
        		            setConnection(null);
        		        }
        				

        			}
        		});
        	}
        	
        });
        
        t.start();
        */
        
        ////String msg = getResources().getString(R.string.connecting_to_server);
        ////dialog = ProgressDialog.show(this, "", msg, true);
        
        new processXmppTask().execute("a", "b", "c");
        
        //setConnection(connection);
                
    }
	
    /*
    private class processXmppTask extends AsyncTask<void, void, void> {
    	
    	@Override
    	protected void doInBackground(void... parmams) {
    		
    	}
    }
    */
    
    private class processXmppTask extends AsyncTask<String, Integer, Long> {
    	
    	@Override
    	protected Long doInBackground(String... urls) {

    		long totalSize = 0;

    		if(D) Log.e(TAG, "++ XMPP connect ++");
	        
			ConnectionConfiguration connConfig =
	        		new ConnectionConfiguration("push.appaas.com", 5222, "push.appaas.com");
	        //connConfig.setSASLAuthenticationEnabled(true);
	        //connConfig.setDebuggerEnabled(true);

			XMPPConnection connection = new XMPPConnection(connConfig);
	        
			try {
	            connection.connect();
	            connection.loginAnonymously();
	            //connection.login("creath", "1234");
	            
	            mUserid = StringUtils.parseName(connection.getUser());
	            
	            ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection);
	            if (sdm == null) sdm = new ServiceDiscoveryManager(connection);    
	            sdm.addFeature("http://jabber.org/protocol/disco#info");
	            sdm.addFeature("jabber:iq:privacy");
	            
	            configure();
	            
		        
		        if (mRoomid == null) {
		        	
		            mRoomid = mUserid;
		            	
		            String room = mRoomid + "@conference.push.appaas.com";
		            mMuc = new MultiUserChat(connection, room);
		            mMuc.join(mNickname);
		            	
		   	        // Send an empty room configuration form which indicates that we want an instant room
		            mMuc.sendConfigurationForm(new Form(Form.TYPE_SUBMIT));
			        

			        mMuc.addMessageListener(packetListener);
			        
			        mMuc.addParticipantStatusListener(participantStatusListener);
			        
			        setConnection(connection);
			           
			          
			        
		        } else {
		            	
		        	String room = mRoomid + "@conference.push.appaas.com";
		        	mMuc = new MultiUserChat(connection, room);
		        	mMuc.join(mNickname);

		            mMuc.addMessageListener(packetListener);
		            mMuc.addParticipantStatusListener(participantStatusListener);
		            
		            setConnection(connection);

		        }
		        


		        try {
		        	String url = "http://push.appaas.com/hulbox/of_join_room.php?roomid=" + mRoomid
		        			+ "&userid=" + mUserid
		        			+ "&nickname=" + URLEncoder.encode(mNickname, "utf-8")
		        			+ "&title=" + URLEncoder.encode(mRoomTitle, "utf-8")
		        			+ "&subtitle=" + URLEncoder.encode(mRoomSubtitle, "utf-8");
			        downloadUrl(url);

	            }catch(Exception e){
	            	Log.d("downloadUrl",e.toString());
	            }    
	            
	        } catch (XMPPException ex) {
	            Log.e("XMPPClient", "[SettingsDialog] Failed to connect to " + connection.getHost());
	            Log.e("XMPPClient", ex.toString());
	            
	            setConnection(null);

	        }
	        
    		///////dialog.dismiss();
	        
    		/////////dialog = null;
    		
    		/*
    		// Add the incoming message to the list view
			mHandler.post(new Runnable() {
				public void run() {
					//setListAdapter();
					mAdapter.notifyDataSetChanged();
					mConversationView.setSelection(messages.size()-1);
				}
			});
    		*/
    		
    		
    		return totalSize;
    	}
    	
    	/*
    	@Override
        protected void onPostExecute(String result) {
    		
    		dialog.dismiss();
    	}
    	*/
    	
    }
    
    
    

    
    // The action listener for the EditText widget, to listen for the return key
    private TextView.OnEditorActionListener mWriteListener =
        new TextView.OnEditorActionListener() {
        public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
            // If the action is a key-up event on the return key, send the message
            if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
                String message = view.getText().toString();
                /////////sendMessage(message);
                
            	mAdapter.add(new OneComment(false, "", message));
            	
            	
            }
            if(D) Log.i(TAG, "END onEditorAction");
            return true;
        }
    };
    
 
 
    
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        
        //inflater.inflate(R.menu.winkroom_menu, menu);
        
        return true;
    }


  
  

    private void setListAdapter() {
        //ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.multi_line_list_item, messages);

    	
    	DiscussArrayAdapter adapter = new DiscussArrayAdapter(this, R.layout.listitem_discuss, messages);
        
        mConversationView.setAdapter(adapter);
        
        mConversationView.setSelection(adapter.getCount() -1);
        
        
    }
    
 
    
    private final DefaultParticipantStatusListener participantStatusListener = new DefaultParticipantStatusListener() {
    
    	public void joined(String participant) {
            super.joined(participant);
            
            
            String msgText;
            String nickname = StringUtils.parseResource(participant);
    		
    		msgText = nickname + getResources().getString(R.string.room_joined);

    		messages.add(new OneComment(true, "", msgText));
    		if (messages.size() > 100) { messages.remove(0); }
    	
    		// Add the incoming message to the list view
    		mHandler.post(new Runnable() {
    			public void run() {
    				//setListAdapter();
    				mAdapter.notifyDataSetChanged();
            		mConversationView.setSelection(messages.size()-1);
    			}
    		});
            
        }
        public void left(String participant) {
            super.left(participant);
            
            
            String msgText;

            String nickname = StringUtils.parseResource(participant);
    		
    		msgText = nickname + getResources().getString(R.string.room_left);

    		messages.add(new OneComment(true, "", msgText));
    		if (messages.size() > 100) { messages.remove(0); }
    		
    		// Add the incoming message to the list view
    		mHandler.post(new Runnable() {
    			public void run() {
    				//setListAdapter();
    				mAdapter.notifyDataSetChanged();
            		mConversationView.setSelection(messages.size()-1);
    			}
    		});
            
        }
    };
    
    
    
     private final PacketListener packetListener = new PacketListener() {
    	
        public void processPacket(Packet packet) {
        	
        	if (packet instanceof Message) {
                // do something
        		Message message = (Message) packet;
        		
        		
        		//if(D) Log.e(TAG, message.getFrom() );
        		
        		
        		if (message.getBody() != null) {
                	
                	if (message.getType() == Message.Type.groupchat) {

                		String fromResource = StringUtils.parseResource(message.getFrom());
                		String fromName = StringUtils.parseBareAddress(fromResource);


                    		String msgText;
                    		msgText = message.getBody();
             
                    		
                    		messages.add(new OneComment(true, fromName, msgText));
                    		if (messages.size() > 100) { messages.remove(0); }
                    		
                    		 //android.os.Message m = new android.os.Message();

                             //mHandler.sendMessage(m);
                    		
                    		
                    		//if (messages.size() > 25) {
                    		if (dialog == null) {	
                    			if(D) Log.e(TAG, "notifyDataSetChanged" );
                    			
                    			// Add the incoming message to the list view
                    			mHandler.post(new Runnable() {
                    				public void run() {
                    					//setListAdapter();
                    					mAdapter.notifyDataSetChanged();
                    					mConversationView.setSelection(messages.size()-1);
                    				}
                    			});
           
                    	}
                    
                	} else {
                		/*
                		String fromResource = StringUtils.parseResource(message.getFrom());
                    	
                    	
                		String fromName = StringUtils.parseBareAddress(fromResource);
                		
                		
                		String msgText;
                		msgText = "(" + getResources().getString(R.string.whisper) + ")" + message.getBody();
           
                		messages.add(new OneComment(true, fromName, msgText));
                		if (messages.size() > 100) { messages.remove(0); }
                		
                		// Add the incoming message to the list view
                		mHandler.post(new Runnable() {
                			public void run() {
                				setListAdapter();
                			}
                		});
                		*/
                	}
        		
        		}
        		
        		
        		
            } else if (packet instanceof Presence) {
              // do something else
            	
            	Presence presence = (Presence) packet;
                
                
                	
                    		String msgText;
                    		msgText = presence.getMode().toString();
               
                    		messages.add(new OneComment(true, presence.getFrom(), msgText));
                    		if (messages.size() > 100) { messages.remove(0); }
                    		
                    		
                    		// Add the incoming message to the list view
                    		mHandler.post(new Runnable() {
                    			public void run() {
                    				setListAdapter();
                    			}
                    		});
                
                
                
                
            }

        	
        	
            
        }
    };
    
    
    
    
    /**
     * Called by Settings dialog when a connection is establised with the XMPP server
     *
     * @param connection
     */
    public void setConnection(XMPPConnection connection) {
        
    	this.connection = connection;
    
      	// Add a packet listener to get messages sent to us
        PacketFilter filter = new MessageTypeFilter(Message.Type.chat);
    	
        //PacketFilter filter = new OrFilter(new MessageTypeFilter(Message.Type.groupchat), 
        	//	new MessageTypeFilter(Message.Type.chat));
    	
        //new OrFilter(new PacketTypeFilter(Message.class), new PacketTypeFilter(Presence.class ))
        
   
        
        connection.addPacketListener(new PacketListener() {
        	
            public void processPacket(Packet packet) {
            	
                Message message = (Message) packet;
                
                if (message.getBody() != null) {
                    
                	
                	if(D) Log.e(TAG, "private chat from " + message.getFrom());
                	
                	
                	String fromResource = StringUtils.parseResource(message.getFrom());
                	
            		String fromName = StringUtils.parseBareAddress(fromResource);
                	
                	//String tt = "CHAT", "Got text [" + message.getBody() + "] from [" + fromName + "]";
                    if(D) Log.e(TAG, "private chat from " + fromName);
                    
 
 

 
                
                    
                    if (mDashDialog.isShowing() == false) {
                    	mDashDialog.setContentView(R.layout.popup2);
                    	
                    	String title = fromName + getResources().getString(R.string.whisper);
                    	mDashDialog.setTitle(title);
    	 
                    	// set the custom dialog components - text, image and button
                    	TextView text = (TextView) mDashDialog.findViewById(R.id.text);
                    	text.setText(message.getBody());
                    	ImageView image = (ImageView) mDashDialog.findViewById(R.id.image);
                    	image.setImageResource(R.drawable.ic_launcher);
    	 
                    	Button dialogButton = (Button) mDashDialog.findViewById(R.id.dialogButtonOK);
                    	// if button is clicked, close the custom dialog
                    	dialogButton.setOnClickListener(new OnClickListener() {
                    		@Override
                    		public void onClick(View v) {
                    			mDashDialog.dismiss();
                    		}
                    	});
    	 
                    	//dlg.show();
                    	mHandler.post(new Runnable() {
                    		public void run() {
                    			mDashDialog.show();
                    		}
                    	});
                    
                    }
                    
                   
                    
                    /*
                    messages.add(new OneComment(true, fromName));
                    if (messages.size() > 100) { messages.remove(0); }
                	// Add the incoming message to the list view
                	mHandler.post(new Runnable() {
                		public void run() {
                			setListAdapter();
                		}
                	});
                	*/

                }
                
                
            }
        }, filter);
    
    
    }
    
    
    
    
    
    //private void configure(ProviderManager pm) {
    private void configure() {
		 
    	ProviderManager pm = ProviderManager.getInstance();
    	
        //  Private Data Storage
        pm.addIQProvider("query","jabber:iq:private", new PrivateDataManager.PrivateDataIQProvider());
 
        //  Time
        try {
            pm.addIQProvider("query","jabber:iq:time", Class.forName("org.jivesoftware.smackx.packet.Time"));
        } catch (ClassNotFoundException e) {
            Log.w("TestClient", "Can't load class for org.jivesoftware.smackx.packet.Time");
        }
 
        
        //  Roster Exchange
        pm.addExtensionProvider("x","jabber:x:roster", new RosterExchangeProvider());
 
        //  Message Events
        pm.addExtensionProvider("x","jabber:x:event", new MessageEventProvider());
 
        //  Chat State
        pm.addExtensionProvider("active","http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
 
        pm.addExtensionProvider("composing","http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
 
        pm.addExtensionProvider("paused","http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
 
        pm.addExtensionProvider("inactive","http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
 
        pm.addExtensionProvider("gone","http://jabber.org/protocol/chatstates", new ChatStateExtension.Provider());
 
        //  XHTML
        //////////pm.addExtensionProvider("html","http://jabber.org/protocol/xhtml-im", new XHTMLExtensionProvider());
 
        //  Group Chat Invitations
        pm.addExtensionProvider("x","jabber:x:conference", new GroupChatInvitation.Provider());
 
        //  Service Discovery # Items    
        pm.addIQProvider("query","http://jabber.org/protocol/disco#items", new DiscoverItemsProvider());
 
        //  Service Discovery # Info
        pm.addIQProvider("query","http://jabber.org/protocol/disco#info", new DiscoverInfoProvider());
 
        //  Data Forms
        pm.addExtensionProvider("x","jabber:x:data", new DataFormProvider());
 
        //  MUC User
        pm.addExtensionProvider("x","http://jabber.org/protocol/muc#user", new MUCUserProvider());
 
        //  MUC Admin    
        pm.addIQProvider("query","http://jabber.org/protocol/muc#admin", new MUCAdminProvider());
 
 
        //  MUC Owner    
        pm.addIQProvider("query","http://jabber.org/protocol/muc#owner", new MUCOwnerProvider());
 
        //  Delayed Delivery
        pm.addExtensionProvider("x","jabber:x:delay", new DelayInformationProvider());
 
        //  Version
        try {
            pm.addIQProvider("query","jabber:iq:version", Class.forName("org.jivesoftware.smackx.packet.Version"));
        } catch (ClassNotFoundException e) {
            //  Not sure what's happening here.
        }
 
        //  VCard
        pm.addIQProvider("vCard","vcard-temp", new VCardProvider());
 
        //  Offline Message Requests
        pm.addIQProvider("offline","http://jabber.org/protocol/offline", new OfflineMessageRequest.Provider());
 
        //  Offline Message Indicator
        pm.addExtensionProvider("offline","http://jabber.org/protocol/offline", new OfflineMessageInfo.Provider());
 
        //  Last Activity
        pm.addIQProvider("query","jabber:iq:last", new LastActivity.Provider());
 
        //  User Search
        pm.addIQProvider("query","jabber:iq:search", new UserSearch.Provider());
 
        //  SharedGroupsInfo
        pm.addIQProvider("sharedgroup","http://www.jivesoftware.org/protocol/sharedgroup", new SharedGroupsInfo.Provider());
 
        //  JEP-33: Extended Stanza Addressing
        pm.addExtensionProvider("addresses","http://jabber.org/protocol/address", new MultipleAddressesProvider());
 		
 
       
        //   FileTransfer
        
        pm.addIQProvider("si","http://jabber.org/protocol/si", new StreamInitiationProvider());
 
        
        pm.addIQProvider("query","http://jabber.org/protocol/bytestreams", new BytestreamsProvider());
 
        //pm.addIQProvider("open","http://jabber.org/protocol/ibb", new IBBProviders.Open());
        //pm.addIQProvider("close","http://jabber.org/protocol/ibb", new IBBProviders.Close());
        //pm.addExtensionProvider("data","http://jabber.org/protocol/ibb", new IBBProviders.Data());
 		
        
        pm.addIQProvider("query","http://jabber.org/protocol/disco#items", new DiscoverItemsProvider());
        pm.addIQProvider("query","http://jabber.org/protocol/disco#info", new DiscoverInfoProvider());

    
        
        
        //  Privacy
        pm.addIQProvider("query","jabber:iq:privacy", new PrivacyProvider());
 
        pm.addIQProvider("command", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider());
        pm.addExtensionProvider("malformed-action", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.MalformedActionError());
        pm.addExtensionProvider("bad-locale", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.BadLocaleError());
        pm.addExtensionProvider("bad-payload", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.BadPayloadError());
        pm.addExtensionProvider("bad-sessionid", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.BadSessionIDError());
        pm.addExtensionProvider("session-expired", "http://jabber.org/protocol/commands", new AdHocCommandDataProvider.SessionExpiredError());
    
        /*
        // PubSub
        pm.addIQProvider(
                "query", "http://jabber.org/protocol/disco#items",
                 new org.jivesoftware.smackx.provider.DiscoverItemsProvider()
            );
            
            pm.addIQProvider("query",
                    "http://jabber.org/protocol/disco#info",
                    new org.jivesoftware.smackx.provider.DiscoverInfoProvider());
            
            pm.addIQProvider("pubsub",
                    "http://jabber.org/protocol/pubsub",
                    new org.jivesoftware.smackx.pubsub.provider.PubSubProvider());

            pm.addExtensionProvider("subscription", PubSubNamespace.BASIC.getXmlns() , new SubscriptionProvider());
            
            pm.addExtensionProvider(
                    "create",
                    "http://jabber.org/protocol/pubsub",
                    new org.jivesoftware.smackx.pubsub.provider.SimpleNodeProvider());
            
            pm.addExtensionProvider("items",
                    "http://jabber.org/protocol/pubsub",
                    new org.jivesoftware.smackx.pubsub.provider.ItemsProvider());
            
            pm.addExtensionProvider("item",
                    "http://jabber.org/protocol/pubsub",
                    new org.jivesoftware.smackx.pubsub.provider.ItemProvider());
            
            pm.addExtensionProvider("item", "",
                    new org.jivesoftware.smackx.pubsub.provider.ItemProvider());
            
            pm.addExtensionProvider(
                            "subscriptions",
                            "http://jabber.org/protocol/pubsub",
                            new org.jivesoftware.smackx.pubsub.provider.SubscriptionsProvider());

            pm.addExtensionProvider(
                            "subscriptions",
                            "http://jabber.org/protocol/pubsub#owner",
                            new org.jivesoftware.smackx.pubsub.provider.SubscriptionsProvider());

            pm.addExtensionProvider(
                            "affiliations",
                            "http://jabber.org/protocol/pubsub",
                            new org.jivesoftware.smackx.pubsub.provider.AffiliationsProvider());
            
            pm.addExtensionProvider(
                            "affiliation",
                            "http://jabber.org/protocol/pubsub",
                            new org.jivesoftware.smackx.pubsub.provider.AffiliationProvider());
            
            pm.addExtensionProvider("options",
                    "http://jabber.org/protocol/pubsub",
                    new org.jivesoftware.smackx.pubsub.provider.FormNodeProvider());
            
            pm.addIQProvider("pubsub",
                    "http://jabber.org/protocol/pubsub#owner",
                    new org.jivesoftware.smackx.pubsub.provider.PubSubProvider());
            
            pm.addExtensionProvider("configure",
                    "http://jabber.org/protocol/pubsub#owner",
                    new org.jivesoftware.smackx.pubsub.provider.FormNodeProvider());
            
            pm.addExtensionProvider("default",
                    "http://jabber.org/protocol/pubsub#owner",
                    new org.jivesoftware.smackx.pubsub.provider.FormNodeProvider());


            pm.addExtensionProvider("event",
                    "http://jabber.org/protocol/pubsub#event",
                    new org.jivesoftware.smackx.pubsub.provider.EventProvider());
            
            pm.addExtensionProvider(
                            "configuration",
                            "http://jabber.org/protocol/pubsub#event",
                            new org.jivesoftware.smackx.pubsub.provider.ConfigEventProvider());
            
            pm.addExtensionProvider(
                            "delete",
                            "http://jabber.org/protocol/pubsub#event",
                            new org.jivesoftware.smackx.pubsub.provider.SimpleNodeProvider());
            
            pm.addExtensionProvider("options",
                    "http://jabber.org/protocol/pubsub#event",
                    new org.jivesoftware.smackx.pubsub.provider.FormNodeProvider());
            
            pm.addExtensionProvider("items",
                    "http://jabber.org/protocol/pubsub#event",
                    new org.jivesoftware.smackx.pubsub.provider.ItemsProvider());
            
            pm.addExtensionProvider("item",
                    "http://jabber.org/protocol/pubsub#event",
                    new org.jivesoftware.smackx.pubsub.provider.ItemProvider());

            pm.addExtensionProvider("headers",
                    "http://jabber.org/protocol/shim",
                    new org.jivesoftware.smackx.provider.HeaderProvider());

            pm.addExtensionProvider("header",
                    "http://jabber.org/protocol/shim",
                    new org.jivesoftware.smackx.provider.HeadersProvider());
            
            
            pm.addExtensionProvider(
                            "retract",
                            "http://jabber.org/protocol/pubsub#event",
                            new org.jivesoftware.smackx.pubsub.provider.RetractEventProvider());
            
            pm.addExtensionProvider(
                            "purge",
                            "http://jabber.org/protocol/pubsub#event",
                            new org.jivesoftware.smackx.pubsub.provider.SimpleNodeProvider());
            

         */


            SmackConfiguration.setKeepAliveInterval(-1);
     
		
	}
 
    
    
    /** A method to download xml data from url */
    private String downloadUrl(String strUrl) throws IOException{
        String data = "";
        InputStream iStream = null;
        try{
                URL url = new URL(strUrl);
                
                // Creating an http connection to communicate with url 
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                // Connecting to url 
                urlConnection.connect();

                // Reading data from url 
                iStream = urlConnection.getInputStream();
                
                BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
                
                StringBuffer sb  = new StringBuffer();
                
                String line = "";
                while( ( line = br.readLine())  != null){
                	sb.append(line);
                }
                
                
                data = sb.toString();

                br.close();

        }catch(Exception e){
                Log.d("Exception while downloading url", e.toString());
                if(D) Log.e(TAG, e.toString());
        }finally{
                iStream.close();
        }

        return data;
    }
    
 
}




